package com.dai.zhenfujin.my.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.Constants.EventConstants;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.base.BaseActivity;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.bean.ProListBean;
import com.dai.zhenfujin.bean.UserBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.my.activity.release.CompanyAddressActivity;
import com.dai.zhenfujin.my.activity.release.CompanyNameActivity;
import com.dai.zhenfujin.my.activity.release.DutyActivity;
import com.dai.zhenfujin.my.activity.release.NameActivity;
import com.dai.zhenfujin.utils.PhotoUtil;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.dai.zhenfujin.visitingcard.app.LocationActiviy;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 名片编辑
 */

public class ReleaseActivity extends BaseActivity implements View.OnClickListener {

    private ImageView imageView, ivHeadPortrait;
    private TextView tvTitle, tvAccomplish, tv_user_desc, tv_phone, tv_weixin;
    private Button bt_save;

    private RelativeLayout rlName, rlSex, rlDuty, rlWorkingRange,
            rlCompanyName, rlCompanyAddress, rlCompanyDetailedAddress, rlUserDesc;
    private TextView tvName, tvSex, tvDuty, tvWorkingRange,
            tvCompanyName, tvCompanyAddress, tvCompanyDetailedAddress;

    private Dialog dialog, dialogHead;

    private String mExtStorDir;

    private final int PERMISSION_READ_AND_CAMERA = 0;//读和相机权限
    private final int PERMISSION_READ = 1;//读取权限
    /* 头像文件 */
    private static final String IMAGE_FILE_NAME = "temp_head_image.jpg";
    private static final String CROP_IMAGE_FILE_NAME = "bala_crop.jpg";

    /* 请求识别码 */
    public static final int CODE_GALLERY_REQUEST = 0xa0;
    public static final int CODE_CAMERA_REQUEST = 0xa1;
    public static final int CODE_RESULT_REQUEST = 0xa2;

    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static int OUTPUT_X = 480;
    private static int OUTPUT_Y = 480;
    //改变头像的标记位
    private int new_icon = 0xa3;
    private ImageView headImage = null;
    private Uri mUriPath;
    private UserBean userBean;
    private String name;
    private String Name;
    private String Sex, Accomplish, CompanyAddress, CompanyName, Duty,
            WorkingRange, tvUserDesc, CompanyDetailedAddress;
    private String trim;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");

    private Uri imageUri;
    private Uri cropImageUri;
    private boolean isShowImg;
    private boolean isShowSex;
    private OSS oss;
    private Double latitude;
    private Double longitude;
    private boolean isShowImgView;
    private boolean isCity;
    private String type_id;
    private RelativeLayout rl_phone, rl_weixin;
    private String headPhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release);
        userBean = (UserBean) getIntent().getSerializableExtra("userBean");

        initView();
        initListener();
    }

    private void initListener() {
        rlName.setOnClickListener(this);
        rlSex.setOnClickListener(this);
        rlDuty.setOnClickListener(this);
        rlWorkingRange.setOnClickListener(this);
        rlCompanyName.setOnClickListener(this);
        rlCompanyAddress.setOnClickListener(this);
        imageView.setOnClickListener(this);
        // tvAccomplish.setOnClickListener(this);
        ivHeadPortrait.setOnClickListener(this);
        bt_save.setOnClickListener(this);
        rlCompanyDetailedAddress.setOnClickListener(this);
        rlUserDesc.setOnClickListener(this); //个性签名
        rl_phone.setOnClickListener(this); //电话
        rl_weixin.setOnClickListener(this); //个性签名
    }

    private void initView() {
        tvTitle = findViewById(R.id.title_textview);
        tvTitle.setText("我的名片");
        imageView = findViewById(R.id.title_imageview);

        tvName = findViewById(R.id.release_text_name);
        tvSex = findViewById(R.id.release_text_sex);
        tvDuty = findViewById(R.id.release_text_duty);
        tvWorkingRange = findViewById(R.id.release_text_working_range);
        tvCompanyName = findViewById(R.id.release_text_company_name);
        tvCompanyAddress = findViewById(R.id.release_text_company_address);
        rlCompanyDetailedAddress = findViewById(R.id.release_company_detailed_address);
        rlUserDesc = findViewById(R.id.rl_user_desc);

        tvCompanyDetailedAddress = findViewById(R.id.tv_detailed_address);
        rlName = findViewById(R.id.release_name);
        rlSex = findViewById(R.id.release_sex);
        rlDuty = findViewById(R.id.release_duty);
        rlWorkingRange = findViewById(R.id.release_working_range);
        rlCompanyName = findViewById(R.id.release_company_name);
        rlCompanyAddress = findViewById(R.id.release_company_address);
        tv_user_desc = findViewById(R.id.tv_user_desc);
        bt_save = findViewById(R.id.bt_save);

        rl_phone = findViewById(R.id.rl_phone); //电话
        rl_weixin = findViewById(R.id.rl_weixin);
        tv_phone = findViewById(R.id.tv_phone);
        tv_weixin = findViewById(R.id.tv_weixin);
        ivHeadPortrait = findViewById(R.id.release_head_portrait);
        String user_id = SPUtils.getString(this, Constants.USER_MOBILE);

        headPhoto = SPUtils.getConversionHeadPhoto(this, user_id);
        if (!TextUtils.isEmpty(headPhoto)) {
            Glide.with(this).load(headPhoto).into(ivHeadPortrait);
        }
        if (!TextUtils.isEmpty(SPUtils.getConversionNickName(this, user_id))) {
            tvName.setText(SPUtils.getConversionNickName(this, user_id));
        }


        if (null != userBean) {
            isShowImg = true;
            Glide.with(this).load(userBean.getUser_logo()).into(ivHeadPortrait);
            tvSex.setText(userBean.getUser_gender());
            tvName.setText(userBean.getUser_name());
            tvDuty.setText(userBean.getUser_duties());
            tv_user_desc.setText(userBean.getUser_desc());//个性签名
            tvWorkingRange.setText(userBean.getUser_job()); //工作范围
            tvCompanyName.setText(userBean.getUser_company());
            tvCompanyAddress.setText(userBean.getUser_region()); //地区
            tvCompanyDetailedAddress.setText(userBean.getUser_address()); //详细地址
            if (!TextUtils.isEmpty(userBean.user_phone))
                tv_phone.setText(userBean.user_phone);
            if (!TextUtils.isEmpty(userBean.user_weixin))
                tv_weixin.setText(userBean.user_weixin);
            tvCompanyDetailedAddress.setText(userBean.getUser_address()); //详细地址
            type_id = userBean.type_id;
            SPUtils.put(this, "latitude2", userBean.loc_y);
            SPUtils.put(this, "longitude2", userBean.loc_x);
        }

        // SPUtils.put(mContext,Constants.USER_LOGO,resultBean.getUser_logo());
        //  SPUtils.put(mContext,Constants.USER_NAME,resultBean.getUser_name());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_imageview://返回
                finish();
                break;
            case R.id.title_tv://完成
                break;
            case R.id.release_head_portrait://头像
                showHeadDialog();
                break;
            case R.id.release_name://姓名
                Intent name = new Intent(this, NameActivity.class);
                if (!TextUtils.isEmpty(tvName.getText().toString().trim()))
                name.putExtra("name",tvName.getText().toString().trim());
                //  startActivity(name);
                  /*
                第一个参数:Intent对象
                第二个参数:请求的一个标识
                 */
                startActivityForResult(name, 1);

                break;
            case R.id.release_sex://性别
                showDialog();
                break;
            case R.id.release_duty://职务
                Intent duty = new Intent(this, DutyActivity.class);
                if (!TextUtils.isEmpty(tvDuty.getText().toString().trim()))
                    duty.putExtra("name",tvDuty.getText().toString().trim());
                startActivityForResult(duty, 2);
                break;
            case R.id.release_working_range://主业
                Intent working_range = new Intent(this, AlumTypeActivity.class);
                if (!TextUtils.isEmpty(tvWorkingRange.getText().toString().trim()))
                    working_range.putExtra("name",tvWorkingRange.getText().toString().trim());
                working_range.putExtra("type", 1);
                startActivityForResult(working_range, 3);

                break;
            case R.id.release_company_name://公司名称
                Intent company_name = new Intent(this, CompanyNameActivity.class);
                if (!TextUtils.isEmpty(tvCompanyName.getText().toString().trim()))
                    company_name.putExtra("name",tvCompanyName.getText().toString().trim());
                startActivityForResult(company_name, 4);
                break;
            case R.id.release_company_address://公司地址
                Intent company_address = new Intent(this, LocationActiviy.class);
                company_address.putExtra("type", 0);
                startActivityForResult(company_address, 5);
                break;

            case R.id.dialog_button1://先生
                dialog.dismiss();
                isShowSex = true;
                tvSex.setText("男");
                break;
            case R.id.dialog_button2://女士
                dialog.dismiss();
                isShowSex = true;
                tvSex.setText("女");
                break;
            case R.id.dialog_button3://取消
                dialog.dismiss();
                break;
            case R.id.dialog_shoot://拍摄
                imageUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(this, "com.dai.zhenfujin.FileProvider", fileUri);
                }
                PhotoUtil.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                dialogHead.dismiss();

                break;
            case R.id.dialog_photo_album://相册
                PhotoUtil.openPic(this, CODE_GALLERY_REQUEST);
                dialogHead.dismiss();
                break;
            case R.id.release_company_detailed_address://详细地址
                Intent intent2 = new Intent(this, CompanyAddressActivity.class);
                if (!TextUtils.isEmpty(tvCompanyDetailedAddress.getText().toString().trim()))
                    intent2.putExtra("name",tvCompanyDetailedAddress.getText().toString().trim());
                intent2.putExtra("type", 7);
                startActivityForResult(intent2, 7);

                break;
            case R.id.rl_user_desc://个性答名
                Intent intent = new Intent(this, CompanyAddressActivity.class);
                if (!TextUtils.isEmpty(tv_user_desc.getText().toString().trim()))
                    intent.putExtra("name",tv_user_desc.getText().toString().trim());
                intent.putExtra("type", 6);
                startActivityForResult(intent, 6);
                break;
            case R.id.rl_phone://电话
                Intent phone = new Intent(this, CompanyAddressActivity.class);
                if (!TextUtils.isEmpty(tv_phone.getText().toString().trim()))
                    phone.putExtra("name",tv_phone.getText().toString().trim());
                phone.putExtra("type", 9);
                startActivityForResult(phone, 9);
                break;
            case R.id.rl_weixin://微信
                Intent weixin = new Intent(this, CompanyAddressActivity.class);
                if (!TextUtils.isEmpty(tv_weixin.getText().toString().trim()))
                    weixin.putExtra("name",tv_weixin.getText().toString().trim());
                weixin.putExtra("type", 10);
                startActivityForResult(weixin, 10);
                break;
            case R.id.dialog_cancel://取消
                dialogHead.dismiss();
            case R.id.bt_save://保存
                Name = tvName.getText().toString().trim();
                Sex = tvSex.getText().toString().trim();
                CompanyAddress = tvCompanyAddress.getText().toString().trim(); //地址
                CompanyName = tvCompanyName.getText().toString().trim(); //公司
                Duty = tvDuty.getText().toString().trim(); //职务
                tvUserDesc = tv_user_desc.getText().toString().trim(); //个性签名
                WorkingRange = tvWorkingRange.getText().toString().trim(); //工作范围
                CompanyDetailedAddress = tvCompanyDetailedAddress.getText().toString().trim(); //详细地址
                if (TextUtils.isEmpty(Name)) {
                    UIUtils.showToastSafe("请输入姓名");
                    return;
                }
                if (TextUtils.isEmpty(Sex)) {
                    UIUtils.showToastSafe("请填写性别");
                    return;
                }
                if (TextUtils.isEmpty(tvUserDesc)) { //个性签名
                    UIUtils.showToastSafe("请输入个性签名");
                    return;
                }
                if (TextUtils.isEmpty(Duty)) {
                    UIUtils.showToastSafe("请输入职务");
                    return;
                }
                if (TextUtils.isEmpty(WorkingRange)) {
                    UIUtils.showToastSafe("请输入工作范围");
                    return;
                }
                if (TextUtils.isEmpty(CompanyName)) {
                    UIUtils.showToastSafe("请输入公司名称");
                    return;
                }
                if (TextUtils.isEmpty(CompanyAddress)) {
                    UIUtils.showToastSafe("请输入公司所在地区");
                    return;
                }

               /* if (TextUtils.isEmpty(CompanyDetailedAddress)) {
                    UIUtils.showToastSafe("请输入公司详细地址");
                    return;
                }*/

                if (isShowImgView) {
                    initOss(); //配置OSS
                    ossToken(revitionImageSize(cropImageUri.getPath()));
                } else {
                    if (null != userBean) {
                        saveUserInfo(userBean.getUser_logo());
                    } else {
                        saveUserInfo(headPhoto);
                    }
                }

                break;
        }
    }

    /**
     * 保存用户信息
     *
     * @param url_log
     */
    private void saveUserInfo(String url_log) {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("user_logo", url_log);
        params2.put("user_gender", Sex);  //男，女
        params2.put("user_company", CompanyName);
        params2.put("user_name", Name);
        params2.put("user_address", CompanyDetailedAddress); //详细地址
        params2.put("user_region", CompanyAddress);  //区域
        params2.put("user_job", WorkingRange);
        params2.put("user_duties", Duty); //职务
        params2.put("user_desc", tvUserDesc);
        params2.put("user_phone", tv_phone.getText().toString().trim());
        params2.put("user_weixin", tv_weixin.getText().toString().trim());
        params2.put("type_id", type_id);  //分类ID

        if (!TextUtils.isEmpty(tv_phone.getText().toString().trim())) {
            if (!UIUtils.isMobileNO(tv_phone.getText().toString().trim())) {
                UIUtils.showToastSafe("请输入正确的手机号码");
                return;
            }
        }


        if (isCity) {
            params2.put("loc_x", longitude + ""); //经度
            params2.put("loc_y", latitude + "");  //  纬度
        } else {
            params2.put("loc_x", SPUtils.getString(this, "longitude2")); //经度
            params2.put("loc_y", SPUtils.getString(this, "latitude2"));  //  纬度
        }

        params.put("req_bd", params2);
        HttpClient.post(this, Constants.UPDATEUSERINFO, params, new CallBack<ProListBean>() {
            @Override
            public void onSuccess(ProListBean resultBean) {
                UIUtils.showToastSafe("发布名片成功");
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setMessageKey(EventConstants.UPDATA_USER_PRODUCT);
                EventBus.getDefault().post(messageEvent);
                //  AlumCardActivity.context.finish();
                finish();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1 && resultCode == 11) {//当请求码是1&&返回码是2进行下面操作
            String name = data.getStringExtra("name");
            tvName.setText(name);
        } else if (requestCode == 2 && resultCode == 12) {
            String duty = data.getStringExtra("duty");
            tvDuty.setText(duty);
        } else if (requestCode == 3 && resultCode == 13) {
            String workingrange = data.getStringExtra("name");
            type_id = data.getStringExtra("type_id");
            tvWorkingRange.setText(workingrange);
        } else if (requestCode == 4 && resultCode == 14) {
            String companyname = data.getStringExtra("companyname");
            tvCompanyName.setText(companyname);
        } else if (requestCode == 5 && resultCode == -1) {  //公司 地址
            latitude = data.getDoubleExtra("latitude", 0);
            longitude = data.getDoubleExtra("longitude", 0);
            String address = data.getStringExtra("address");
            tvCompanyAddress.setText(address);
            isCity = true;
            SPUtils.put(this, "latitude2", latitude + "");
            SPUtils.put(this, "latitude2", longitude + "");

        } else if (requestCode == 6 && resultCode == 15) { //个性签名
            String companyaddress = data.getStringExtra("companyaddress");
            tv_user_desc.setText(companyaddress);
        } else if (requestCode == 7 && resultCode == 15) { //详细地址
            String companyaddress = data.getStringExtra("companyaddress");
            tvCompanyDetailedAddress.setText(companyaddress);
        } else if (requestCode == 9 && resultCode == 15) { //详细地址
            String companyaddress = data.getStringExtra("companyaddress");
            tv_phone.setText(companyaddress);
        } else if (requestCode == 10 && resultCode == 15) { //详细地址
            String companyaddress = data.getStringExtra("companyaddress");
            tv_weixin.setText(companyaddress);
        }

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtil.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtil.getPath(this, data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(this, "com.dai.zhenfujin.FileProvider", new File(newUri.getPath()));
                    }
                    PhotoUtil.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_RESULT_REQUEST:
                    isShowImgView = true;
                    Bitmap bitmap = PhotoUtil.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        showImages(bitmap);
                    }
                    break;
                default:
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void showImages(Bitmap bitmap) {
        isShowImg = true;
        ivHeadPortrait.setImageBitmap(bitmap);
    }

    private void ossToken(String path) {
        // 构造上传请求
        final String imgName = UIUtils.getCurTimeMills() + "";
        PutObjectRequest put = new PutObjectRequest("zenfujin-bucket", "profile/" + imgName + ".jpg", path);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
                String url_log = "https://image.zhenfujin.net/" + "profile/" + imgName + ".jpg";
                runOnUiThread(() -> saveUserInfo(url_log));
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("onFailure", serviceException.getErrorCode());
                    Log.e("onFailure", serviceException.getRequestId());
                    Log.e("onFailure", serviceException.getHostId());
                    Log.e("onFailure", serviceException.getRawMessage());
                    UIUtils.showToastSafe("图片上传失败，请重新上传");
                }
            }
        });
    }

    private void initOss() {
        String endpoint = "http://oss-cn-zhangjiakou.aliyuncs.com";
        // 在移动端建议使用STS方式初始化OSSClient。
        // 更多信息可查看sample 中 sts 使用方式(https://github.com/aliyun/aliyun-oss-android-sdk/tree/master/app/src/main/java/com/alibaba/sdk/android/oss/app)
        //   OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(Constants.ACCESS_ID, Constants.ACCESS_KEY);

        //该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

        OSSLog.enableLog();
        oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
    }

    private String revitionImageSize(String path) {
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            in = new BufferedInputStream(new FileInputStream(
                    new File(path)));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true; //只读取图片，不加载到内存中
            BitmapFactory.decodeStream(in, null, options);
            in.close();

            options.inJustDecodeBounds = false;
            int w = options.outWidth;
            int h = options.outHeight;
            float hh = 800f;//
            float ww = 480f;//
            int be = 1;
            if (w > h && w > ww) {
                be = (int) (options.outWidth / ww);
            } else if (w < h && h > hh) {
                be = (int) (options.outHeight / hh);
            }
            if (be <= 0)
                be = 1;
            options.inSampleSize = be;//设置采样率

            options.inPreferredConfig = Bitmap.Config.ARGB_8888;//该模式是默认的,可不设
            options.inPurgeable = true;// 同时设置才会有效
            options.inInputShareable = true;//。当系统内存不够时候图片自动被回收
            String newPath = Constants.APP_FOLD + path.substring(path.lastIndexOf("/"));
            saveBitmapToFile(bitmap, newPath);
            // bitmap = BitmapFactory.decodeFile(path, options);
            return newPath;
        } catch (Exception e) {
            e.printStackTrace();
            return path;
        }
    }

    /**
     * 保存图片
     *
     * @param bitmap
     * @param _file
     * @throws IOException
     */
    public void saveBitmapToFile(Bitmap bitmap, String _file)
            throws IOException {
        BufferedOutputStream os = null;
        try {
            File file = new File(_file);
            int end = _file.lastIndexOf(File.separator);
            String _filePath = _file.substring(0, end);
            File filePath = new File(_filePath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            file.createNewFile();
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private void showHeadDialog() {
        dialogHead = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_head_portrait, null);
        view.findViewById(R.id.dialog_shoot).setOnClickListener(this);
        view.findViewById(R.id.dialog_photo_album).setOnClickListener(this);
        view.findViewById(R.id.dialog_cancel).setOnClickListener(this);
        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        dialogHead.show();//显示对话框//设置Dialog从窗体底部弹出
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
        //将属性设置给窗体
        window.setAttributes(lp);

    }

    private void showDialog() {
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_popwindow, null);
        //初始控件
        view.findViewById(R.id.dialog_button1).setOnClickListener(this);
        view.findViewById(R.id.dialog_button2).setOnClickListener(this);
        view.findViewById(R.id.dialog_button3).setOnClickListener(this);
        //将布局设置给Dialog
        dialog.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        if (dialogWindow == null) {
            return;
        }
        dialog.show();//显示对话框//设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
        //将属性设置给窗体
        dialogWindow.setAttributes(lp);
    }
}


